<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/logo1.jpg?v=7.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/logo1.jpg?v=7.1.0">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.0" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="Golang Channel">
<meta name="keywords" content="Channel">
<meta property="og:type" content="article">
<meta property="og:title" content="GolangChannel">
<meta property="og:url" content="https://luoo.oschina.io/2017/09/09/tech/GolangChannel/index.html">
<meta property="og:site_name" content="从你的全世界路过">
<meta property="og:description" content="Golang Channel">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-04-14T12:28:00.709Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="GolangChannel">
<meta name="twitter:description" content="Golang Channel">



  <link rel="alternate" href="/atom.xml" title="从你的全世界路过" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://luoo.oschina.io/2017/09/09/tech/GolangChannel/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>GolangChannel | 从你的全世界路过</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">从你的全世界路过</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">心智渐开，世事渐杂</p>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-schedule">

    
    
    
      
    

    

    <a href="/schedule/" rel="section"><i class="menu-item-icon fa fa-fw fa-calendar"></i> <br>计划</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-you">

    
    
    
      
    

    

    <a href="/you/" rel="section"><i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>知遇</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://luoo.oschina.io/2017/09/09/tech/GolangChannel/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="方林">
      <meta itemprop="description" content="愿你出走半生，归来仍是少年">
      <meta itemprop="image" content="/images/logo1.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="从你的全世界路过">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">GolangChannel

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2017-09-09 15:05:25" itemprop="dateCreated datePublished" datetime="2017-09-09T15:05:25+08:00">2017-09-09</time>
            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/编程技术/" itemprop="url" rel="index"><span itemprop="name">编程技术</span></a></span>

                
                
              
            </span>
          

          
            
            
              
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
            
                <span class="post-meta-item-text">评论数：</span>
                <a href="/2017/09/09/tech/GolangChannel/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2017/09/09/tech/GolangChannel/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Golang Channel</p>
<a id="more"></a>
<h3 id="Golang并发基础理论"><a href="#Golang并发基础理论" class="headerlink" title="Golang并发基础理论"></a>Golang并发基础理论</h3><p>Golang在并发设计方面参考了 C.A.R Hoare 的CSP，即Communicating Sequential Processes并发模型理论。<br>维基百科中概要罗列了CSP模型与另外一种并发模型Actor模型的区别：Actor模型广义上讲与CSP模型很相似。<br>但两种模型就提供的原语而言，又有一些根本上的不同之处：<br>– CSP模型处理过程是匿名的，而Actor模型中的Actor则具有身份标识。<br>– CSP模型的消息传递在收发消息进程间包含了一个交会点，即发送方只能在接收方准备好接收消息时才能发送消息。相反，actor模型中的消息传递是异步 的，即消息的发送和接收无需在同一时间进行，发送方可以在接收方准备好接收消息前将消息发送出去。这两种方案可以认为是彼此对偶的。在某种意义下，基于交 会点的系统可以通过构造带缓冲的通信的方式来模拟异步消息系统。而异步系统可以通过构造带消息/应答协议的方式来同步发送方和接收方来模拟交会点似的通信 方式。<br>– CSP使用显式的Channel用于消息传递，而Actor模型则将消息发送给命名的目的Actor。这两种方法可以被认为是对偶的。某种意义下，进程可 以从一个实际上拥有身份标识的channel接收消息，而通过将actors构造成类Channel的行为模式也可以打破actors之间的名字耦合。</p>
<h3 id="Go-Channel基本语法"><a href="#Go-Channel基本语法" class="headerlink" title="Go Channel基本语法"></a>Go Channel基本语法</h3><p>Go Channel的基本操作语法如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">c := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">bool</span>) <span class="comment">//创建一个无缓冲的bool型Channel</span></span><br><span class="line">c &lt;- x        <span class="comment">//向一个Channel发送一个值</span></span><br><span class="line">&lt;- c          <span class="comment">//从一个Channel中接收一个值</span></span><br><span class="line">x = &lt;- c      <span class="comment">//从Channel c接收一个值并将其存储到x中</span></span><br><span class="line">x, ok = &lt;- c  <span class="comment">//从Channel接收一个值，如果channel关闭了或没有数据，那么ok将被置为false</span></span><br></pre></td></tr></table></figure>
<p>不带缓冲的Channel兼具通信和同步两种特性，颇受青睐。</p>
<h3 id="Channel-用作信号量（Signal）"><a href="#Channel-用作信号量（Signal）" class="headerlink" title="Channel 用作信号量（Signal）"></a>Channel 用作信号量（Signal）</h3><h4 id="等待一个事件（Event）"><a href="#等待一个事件（Event）" class="headerlink" title="等待一个事件（Event）"></a>等待一个事件（Event）</h4><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        fmt.Println(<span class="string">"Begin doing something!"</span>)</span><br><span class="line">        c := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">bool</span>)</span><br><span class="line">        <span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">                fmt.Println(<span class="string">"Doing something…"</span>)</span><br><span class="line">                <span class="built_in">close</span>(c)</span><br><span class="line">        &#125;()</span><br><span class="line">        &lt;-c</span><br><span class="line">        fmt.Println(<span class="string">"Done!"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里main goroutine通过”&lt;-c”来等待sub goroutine中的“完成事件”，sub goroutine通过close channel促发这一事件。当然也可以通过向Channel写入一个bool值的方式来作为事件通知。main goroutine在channel c上没有任何数据可读的情况下会阻塞等待。</p>
<p>关于输出结果：</p>
<p>根据《Go memory model》中关于close channel与recv from channel的order的定义：The closing of a channel happens before a receive that returns a zero value because the channel is closed.</p>
<p>我们可以很容易判断出上面程序的输出结果：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Begin doing something!</span><br><span class="line">Doing something…</span><br><span class="line">Done!</span><br></pre></td></tr></table></figure>
<p>如果将close(c)换成c&lt;-true，则根据《Go memory model》中的定义：A receive from an unbuffered channel happens before the send on that channel completes.<br>“&lt;-c”要先于”c&lt;-true”完成，但也不影响日志的输出顺序，输出结果仍为上面三行。</p>
<h4 id="协同多个Goroutines"><a href="#协同多个Goroutines" class="headerlink" title="协同多个Goroutines"></a>协同多个Goroutines</h4><p>同上，close channel还可以用于协同多个Goroutines，比如下面这个例子，我们创建了100个Worker Goroutine，这些Goroutine在被创建出来后都阻塞在”&lt;-start”上，直到我们在main goroutine中给出开工的信号：”close(start)”，这些goroutines才开始真正的并发运行起来。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">worker</span><span class="params">(start <span class="keyword">chan</span> <span class="keyword">bool</span>, index <span class="keyword">int</span>)</span></span> &#123;</span><br><span class="line">        &lt;-start</span><br><span class="line">        fmt.Println(<span class="string">"This is Worker:"</span>, index)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        start := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">bool</span>)</span><br><span class="line">        <span class="keyword">for</span> i := <span class="number">1</span>; i &lt;= <span class="number">100</span>; i++ &#123;</span><br><span class="line">                <span class="keyword">go</span> worker(start, i)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">close</span>(start)</span><br><span class="line">        <span class="keyword">select</span> &#123;&#125; <span class="comment">//deadlock we expected</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="Select"><a href="#Select" class="headerlink" title="Select"></a>Select</h4><h5 id="select的基本操作"><a href="#select的基本操作" class="headerlink" title="select的基本操作"></a>select的基本操作</h5><p>select是Go语言特有的操作，使用select我们可以同时在多个channel上进行发送/接收操作。下面是select的基本操作。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> &#123;</span><br><span class="line">        <span class="keyword">case</span> x := &lt;- somechan:</span><br><span class="line">        <span class="comment">// … 使用x进行一些操作</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">case</span> y, ok := &lt;- someOtherchan:</span><br><span class="line">        <span class="comment">// … 使用y进行一些操作，</span></span><br><span class="line">        <span class="comment">// 检查ok值判断someOtherchan是否已经关闭</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">case</span> outputChan &lt;- z:</span><br><span class="line">        <span class="comment">// … z值被成功发送到Channel上时</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">        <span class="comment">// … 上面case均无法通信时，执行此分支</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="for-select"><a href="#for-select" class="headerlink" title="for/select"></a>for/select</h5><p>我们在使用select时很少只是对其进行一次evaluation，我们常常将其与for {}结合在一起使用，并选择适当时机从for{}中退出。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> &#123;</span><br><span class="line">        <span class="keyword">select</span> &#123;</span><br><span class="line">        <span class="keyword">case</span> x := &lt;- somechan:</span><br><span class="line">            <span class="comment">// … 使用x进行一些操作</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">case</span> y, ok := &lt;- someOtherchan:</span><br><span class="line">            <span class="comment">// … 使用y进行一些操作，</span></span><br><span class="line">            <span class="comment">// 检查ok值判断someOtherchan是否已经关闭</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">case</span> outputChan &lt;- z:</span><br><span class="line">            <span class="comment">// … z值被成功发送到Channel上时</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="comment">// … 上面case均无法通信时，执行此分支</span></span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="终结workers"><a href="#终结workers" class="headerlink" title="终结workers"></a>终结workers</h5><p>下面是一个常见的终结sub worker goroutines的方法，每个worker goroutine通过select监视一个die channel来及时获取main goroutine的退出通知。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"time"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">worker</span><span class="params">(die <span class="keyword">chan</span> <span class="keyword">bool</span>, index <span class="keyword">int</span>)</span></span> &#123;</span><br><span class="line">        fmt.Println(<span class="string">"Begin: This is Worker:"</span>, index)</span><br><span class="line">        <span class="keyword">for</span> &#123;</span><br><span class="line">                <span class="keyword">select</span> &#123;</span><br><span class="line">                        <span class="comment">//case xx：</span></span><br><span class="line">                        <span class="comment">//做事的分支</span></span><br><span class="line">                        <span class="keyword">case</span> &lt;-die:</span><br><span class="line">                        fmt.Println(<span class="string">"Done: This is Worker:"</span>, index)</span><br><span class="line">                        <span class="keyword">return</span></span><br><span class="line">                &#125;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        die := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">bool</span>)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> i := <span class="number">1</span>; i &lt;= <span class="number">100</span>; i++ &#123;</span><br><span class="line">                <span class="keyword">go</span> worker(die, i)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        time.Sleep(time.Second * <span class="number">5</span>)</span><br><span class="line">        <span class="built_in">close</span>(die)</span><br><span class="line">        <span class="keyword">select</span> &#123;&#125; <span class="comment">//deadlock we expected</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="终结验证"><a href="#终结验证" class="headerlink" title="终结验证"></a>终结验证</h5><p>有时候终结一个worker后，main goroutine想确认worker routine是否真正退出了，可采用下面这种方法：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="comment">//"time"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">worker</span><span class="params">(die <span class="keyword">chan</span> <span class="keyword">bool</span>)</span></span> &#123;</span><br><span class="line">        fmt.Println(<span class="string">"Begin: This is Worker"</span>)</span><br><span class="line">        <span class="keyword">for</span> &#123;</span><br><span class="line">                <span class="keyword">select</span> &#123;</span><br><span class="line">                        <span class="comment">//case xx：</span></span><br><span class="line">                        <span class="comment">//做事的分支</span></span><br><span class="line">                        <span class="keyword">case</span> &lt;-die:</span><br><span class="line">                                fmt.Println(<span class="string">"Done: This is Worker"</span>)</span><br><span class="line">                                die &lt;- <span class="literal">true</span></span><br><span class="line">                                <span class="keyword">return</span></span><br><span class="line">                &#125;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        die := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">bool</span>)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">go</span> worker(die)</span><br><span class="line"></span><br><span class="line">        die &lt;- <span class="literal">true</span></span><br><span class="line">        &lt;-die</span><br><span class="line">        fmt.Println(<span class="string">"Worker goroutine has been terminated"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="关闭的Channel永远不会阻塞"><a href="#关闭的Channel永远不会阻塞" class="headerlink" title="关闭的Channel永远不会阻塞"></a>关闭的Channel永远不会阻塞</h5><p>下面演示在一个已经关闭了的channel上读写的结果：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        cb := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">bool</span>)</span><br><span class="line">        <span class="built_in">close</span>(cb)</span><br><span class="line">        x := &lt;-cb</span><br><span class="line">        fmt.Printf(<span class="string">"%#v\n"</span>, x)</span><br><span class="line"></span><br><span class="line">        x, ok := &lt;-cb</span><br><span class="line">        fmt.Printf(<span class="string">"%#v %#v\n"</span>, x, ok)</span><br><span class="line"></span><br><span class="line">        ci := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>)</span><br><span class="line">        <span class="built_in">close</span>(ci)</span><br><span class="line">        y := &lt;-ci</span><br><span class="line">        fmt.Printf(<span class="string">"%#v\n"</span>, y)</span><br><span class="line"></span><br><span class="line">        cb &lt;- <span class="literal">true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看到在一个已经close的unbuffered channel上执行读操作，回返回channel对应类型的零值，比如bool型channel返回false，int型channel返回0。但向close的channel写则会触发panic。不过无论读写都不会导致阻塞。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span>go run testoperateonclosedchannel.go</span><br><span class="line">false</span><br><span class="line">false false</span><br><span class="line">0</span><br><span class="line">panic: runtime error: send on closed channel</span><br></pre></td></tr></table></figure>
<h5 id="关闭带缓存的channel"><a href="#关闭带缓存的channel" class="headerlink" title="关闭带缓存的channel"></a>关闭带缓存的channel</h5><p>将unbuffered channel换成buffered channel会怎样？我们看下面例子：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        c := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>, <span class="number">3</span>)</span><br><span class="line">        c &lt;- <span class="number">15</span></span><br><span class="line">        c &lt;- <span class="number">34</span></span><br><span class="line">        c &lt;- <span class="number">65</span></span><br><span class="line">        <span class="built_in">close</span>(c)</span><br><span class="line">        fmt.Printf(<span class="string">"%d\n"</span>, &lt;-c)</span><br><span class="line">        fmt.Printf(<span class="string">"%d\n"</span>, &lt;-c)</span><br><span class="line">        fmt.Printf(<span class="string">"%d\n"</span>, &lt;-c)</span><br><span class="line">        fmt.Printf(<span class="string">"%d\n"</span>, &lt;-c)</span><br><span class="line"></span><br><span class="line">        c &lt;- <span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看出带缓冲的channel略有不同。尽管已经close了，但我们依旧可以从中读出关闭前写入的3个值。第四次读取时，则会返回该channel类型的零值。向这类channel写入操作也会触发panic。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span>go run testclosedbufferedchannel.go</span><br><span class="line">15</span><br><span class="line">34</span><br><span class="line">65</span><br><span class="line">0</span><br><span class="line">panic: runtime error: send on closed channel</span><br></pre></td></tr></table></figure>
<h5 id="range"><a href="#range" class="headerlink" title="range"></a>range</h5><p>Golang中的range常常和channel并肩作战，它被用来从channel中读取所有值。下面是一个简单的实例：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">generator</span><span class="params">(strings <span class="keyword">chan</span> <span class="keyword">string</span>)</span></span> &#123;</span><br><span class="line">        strings &lt;- <span class="string">"Five hour's New York jet lag"</span></span><br><span class="line">        strings &lt;- <span class="string">"and Cayce Pollard wakes in Camden Town"</span></span><br><span class="line">        strings &lt;- <span class="string">"to the dire and ever-decreasing circles"</span></span><br><span class="line">        strings &lt;- <span class="string">"of disrupted circadian rhythm."</span></span><br><span class="line">        <span class="built_in">close</span>(strings)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        strings := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">string</span>)</span><br><span class="line">        <span class="keyword">go</span> generator(strings)</span><br><span class="line">        <span class="keyword">for</span> s := <span class="keyword">range</span> strings &#123;</span><br><span class="line">                fmt.Printf(<span class="string">"%s\n"</span>, s)</span><br><span class="line">        &#125;</span><br><span class="line">        fmt.Printf(<span class="string">"\n"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="隐藏状态"><a href="#隐藏状态" class="headerlink" title="隐藏状态"></a>隐藏状态</h3><p>下面通过一个例子来演示一下channel如何用来隐藏状态：<br>唯一的ID服务：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">newUniqueIDService</span><span class="params">()</span> &lt;-<span class="title">chan</span> <span class="title">string</span></span> &#123;</span><br><span class="line">        id := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">string</span>)</span><br><span class="line">        <span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">                <span class="keyword">var</span> counter <span class="keyword">int64</span> = <span class="number">0</span></span><br><span class="line">                <span class="keyword">for</span> &#123;</span><br><span class="line">                        id &lt;- fmt.Sprintf(<span class="string">"%x"</span>, counter)</span><br><span class="line">                        counter += <span class="number">1</span></span><br><span class="line">                &#125;</span><br><span class="line">        &#125;()</span><br><span class="line">        <span class="keyword">return</span> id</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        id := newUniqueIDService()</span><br><span class="line">        <span class="keyword">for</span> i := <span class="number">0</span>; i &lt; <span class="number">10</span>; i++ &#123;</span><br><span class="line">                fmt.Println(&lt;-id)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>newUniqueIDService通过一个channel与main goroutine关联，main goroutine无需知道uniqueid实现的细节以及当前状态，只需通过channel获得最新id即可。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span> go run testuniqueid.go</span><br><span class="line">0</span><br><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td></tr></table></figure>
<h3 id="默认情况"><a href="#默认情况" class="headerlink" title="默认情况"></a>默认情况</h3><p>我想这里John Graham-Cumming主要是想告诉我们select的default分支的实践用法。</p>
<h4 id="select-for-non-blocking-receive"><a href="#select-for-non-blocking-receive" class="headerlink" title="select for non-blocking receive"></a>select for non-blocking receive</h4><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">idle:= <span class="built_in">make</span>(<span class="keyword">chan</span> []<span class="keyword">byte</span>, <span class="number">5</span>) <span class="comment">//用一个带缓冲的channel构造一个简单的队列</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">select</span> &#123;</span><br><span class="line">        <span class="keyword">case</span> b = &lt;-idle:<span class="comment">//尝试从idle队列中读取</span></span><br><span class="line">        …</span><br><span class="line">        <span class="keyword">default</span>:  <span class="comment">//队列空，分配一个新的buffer</span></span><br><span class="line">                makes += <span class="number">1</span></span><br><span class="line">                b = <span class="built_in">make</span>([]<span class="keyword">byte</span>, size)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="select-for-non-blocking-send"><a href="#select-for-non-blocking-send" class="headerlink" title="select for non-blocking send"></a>select for non-blocking send</h4><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">idle:= <span class="built_in">make</span>(<span class="keyword">chan</span> []<span class="keyword">byte</span>, <span class="number">5</span>) <span class="comment">//用一个带缓冲的channel构造一个简单的队列</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">select</span> &#123;</span><br><span class="line">        <span class="keyword">case</span> idle &lt;- b: <span class="comment">//尝试向队列中插入一个buffer</span></span><br><span class="line">                <span class="comment">//…</span></span><br><span class="line">        <span class="keyword">default</span>: <span class="comment">//队列满？</span></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Nil-Channels"><a href="#Nil-Channels" class="headerlink" title="Nil Channels"></a>Nil Channels</h3><h4 id="Nil-Channels阻塞"><a href="#Nil-Channels阻塞" class="headerlink" title="Nil Channels阻塞"></a>Nil Channels阻塞</h4><p>对一个没有初始化的channel进行读写操作都将发生阻塞，例子如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">var</span> c <span class="keyword">chan</span> <span class="keyword">int</span></span><br><span class="line">        &lt;-c</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span>go run testnilchannel.go</span><br><span class="line">fatal error: all goroutines are asleep – deadlock!</span><br></pre></td></tr></table></figure>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">var</span> c <span class="keyword">chan</span> <span class="keyword">int</span></span><br><span class="line">        c &lt;- <span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span>go run testnilchannel.go</span><br><span class="line">fatal error: all goroutines are asleep – deadlock!</span><br></pre></td></tr></table></figure>
<h4 id="Nil-Channel在select中的使用"><a href="#Nil-Channel在select中的使用" class="headerlink" title="Nil Channel在select中的使用"></a>Nil Channel在select中的使用</h4><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">"time"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">var</span> c1, c2 <span class="keyword">chan</span> <span class="keyword">int</span> = <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>), <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>)</span><br><span class="line">        <span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">                time.Sleep(time.Second * <span class="number">5</span>)</span><br><span class="line">                c1 &lt;- <span class="number">5</span></span><br><span class="line">                <span class="built_in">close</span>(c1)</span><br><span class="line">        &#125;()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">                time.Sleep(time.Second * <span class="number">7</span>)</span><br><span class="line">                c2 &lt;- <span class="number">7</span></span><br><span class="line">                <span class="built_in">close</span>(c2)</span><br><span class="line">        &#125;()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> &#123;</span><br><span class="line">                <span class="keyword">select</span> &#123;</span><br><span class="line">                <span class="keyword">case</span> x := &lt;-c1:</span><br><span class="line">                        fmt.Println(x)</span><br><span class="line">                <span class="keyword">case</span> x := &lt;-c2:</span><br><span class="line">                        fmt.Println(x)</span><br><span class="line">                &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        fmt.Println(<span class="string">"over"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们原本期望程序交替输出5和7两个数字，但实际的输出结果却是：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">5</span><br><span class="line">0</span><br><span class="line">0</span><br><span class="line">0</span><br><span class="line">...0 死循环</span><br></pre></td></tr></table></figure>
<p>再仔细分析代码，原来select每次按case顺序evaluate：</p>
<p>– 前5s，select一直阻塞；<br>– 第5s，c1返回一个5后被close了，“case x := &lt;-c1”这个分支返回，select输出5，并重新select<br>– 下一轮select又从“case x := &lt;-c1”这个分支开始evaluate，由于c1被close，按照前面的知识，close的channel不会阻塞，我们会读出这个 channel对应类型的零值，这里就是0；select再次输出0；这时即便c2有值返回，程序也不会走到c2这个分支<br>– 依次类推，程序无限循环的输出0<br>我们利用nil channel来改进这个程序，以实现我们的意图，代码如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">"time"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">var</span> c1, c2 <span class="keyword">chan</span> <span class="keyword">int</span> = <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>), <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="keyword">int</span>)</span><br><span class="line">        <span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">                time.Sleep(time.Second * <span class="number">5</span>)</span><br><span class="line">                c1 &lt;- <span class="number">5</span></span><br><span class="line">                <span class="built_in">close</span>(c1)</span><br><span class="line">        &#125;()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">                time.Sleep(time.Second * <span class="number">7</span>)</span><br><span class="line">                c2 &lt;- <span class="number">7</span></span><br><span class="line">                <span class="built_in">close</span>(c2)</span><br><span class="line">        &#125;()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> &#123;</span><br><span class="line">                <span class="keyword">select</span> &#123;</span><br><span class="line">                <span class="keyword">case</span> x, ok := &lt;-c1:</span><br><span class="line">                        <span class="keyword">if</span> !ok &#123;</span><br><span class="line">                                c1 = <span class="literal">nil</span></span><br><span class="line">                        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                                fmt.Println(x)</span><br><span class="line">                        &#125;</span><br><span class="line">                <span class="keyword">case</span> x, ok := &lt;-c2:</span><br><span class="line">                        <span class="keyword">if</span> !ok &#123;</span><br><span class="line">                                c2 = <span class="literal">nil</span></span><br><span class="line">                        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                                fmt.Println(x)</span><br><span class="line">                        &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">if</span> c1 == <span class="literal">nil</span> &amp;&amp; c2 == <span class="literal">nil</span> &#123;</span><br><span class="line">                        <span class="keyword">break</span></span><br><span class="line">                &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        fmt.Println(<span class="string">"over"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看出：通过将已经关闭的channel置为nil，下次select将会阻塞在该channel上，使得select继续下面的分支evaluation。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span>go run testnilchannel.go</span><br><span class="line">5</span><br><span class="line">7</span><br><span class="line">over</span><br></pre></td></tr></table></figure>
<h3 id="Timers"><a href="#Timers" class="headerlink" title="Timers"></a>Timers</h3><h4 id="超时机制Timeout"><a href="#超时机制Timeout" class="headerlink" title="超时机制Timeout"></a>超时机制Timeout</h4><p>带超时机制的select是常规的tip，下面是示例代码，实现30s的超时select：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">worker</span><span class="params">(start <span class="keyword">chan</span> <span class="keyword">bool</span>)</span></span> &#123;</span><br><span class="line">        timeout := time.After(<span class="number">30</span> * time.Second)</span><br><span class="line">        <span class="keyword">for</span> &#123;</span><br><span class="line">                <span class="keyword">select</span> &#123;</span><br><span class="line">                        <span class="comment">// … do some stuff</span></span><br><span class="line">                <span class="keyword">case</span> &lt;- timeout:</span><br><span class="line">                        <span class="keyword">return</span></span><br><span class="line">                &#125;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="心跳HeartBeart"><a href="#心跳HeartBeart" class="headerlink" title="心跳HeartBeart"></a>心跳HeartBeart</h4><p>与timeout实现类似，下面是一个简单的心跳select实现：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">worker</span><span class="params">(start <span class="keyword">chan</span> <span class="keyword">bool</span>)</span></span> &#123;</span><br><span class="line">        heartbeat := time.Tick(<span class="number">30</span> * time.Second)</span><br><span class="line">        <span class="keyword">for</span> &#123;</span><br><span class="line">                <span class="keyword">select</span> &#123;</span><br><span class="line">                     <span class="comment">// … do some stuff</span></span><br><span class="line">                <span class="keyword">case</span> &lt;- heartbeat:</span><br><span class="line">                    <span class="comment">//… do heartbeat stuff</span></span><br><span class="line">                &#125;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Channel/" rel="tag"># Channel</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/09/09/tech/微服务架构概念解读/" rel="next" title="微服务架构概念解读">
                <i class="fa fa-chevron-left"></i> 微服务架构概念解读
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/09/29/tech/Algorithm Implemented In Golang/" rel="prev" title="Algorithm Implemented In Golang">
                Algorithm Implemented In Golang <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/logo1.jpg" alt="方林">
            
              <p class="site-author-name" itemprop="name">方林</p>
              <div class="site-description motion-element" itemprop="description">愿你出走半生，归来仍是少年</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">27</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">3</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">17</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/yourname" title="GitHub &rarr; https://github.com/yourname" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="mailto:sean_ps@163.com" title="E-Mail &rarr; mailto:sean_ps@163.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            </div>
          

          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.luoo.net" title="http://www.luoo.net" rel="noopener" target="_blank">落网</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Golang并发基础理论"><span class="nav-number">1.</span> <span class="nav-text">Golang并发基础理论</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Go-Channel基本语法"><span class="nav-number">2.</span> <span class="nav-text">Go Channel基本语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Channel-用作信号量（Signal）"><span class="nav-number">3.</span> <span class="nav-text">Channel 用作信号量（Signal）</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#等待一个事件（Event）"><span class="nav-number">3.1.</span> <span class="nav-text">等待一个事件（Event）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#协同多个Goroutines"><span class="nav-number">3.2.</span> <span class="nav-text">协同多个Goroutines</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Select"><span class="nav-number">3.3.</span> <span class="nav-text">Select</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#select的基本操作"><span class="nav-number">3.3.1.</span> <span class="nav-text">select的基本操作</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#for-select"><span class="nav-number">3.3.2.</span> <span class="nav-text">for/select</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#终结workers"><span class="nav-number">3.3.3.</span> <span class="nav-text">终结workers</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#终结验证"><span class="nav-number">3.3.4.</span> <span class="nav-text">终结验证</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#关闭的Channel永远不会阻塞"><span class="nav-number">3.3.5.</span> <span class="nav-text">关闭的Channel永远不会阻塞</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#关闭带缓存的channel"><span class="nav-number">3.3.6.</span> <span class="nav-text">关闭带缓存的channel</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#range"><span class="nav-number">3.3.7.</span> <span class="nav-text">range</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#隐藏状态"><span class="nav-number">4.</span> <span class="nav-text">隐藏状态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#默认情况"><span class="nav-number">5.</span> <span class="nav-text">默认情况</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#select-for-non-blocking-receive"><span class="nav-number">5.1.</span> <span class="nav-text">select for non-blocking receive</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#select-for-non-blocking-send"><span class="nav-number">5.2.</span> <span class="nav-text">select for non-blocking send</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Nil-Channels"><span class="nav-number">6.</span> <span class="nav-text">Nil Channels</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Nil-Channels阻塞"><span class="nav-number">6.1.</span> <span class="nav-text">Nil Channels阻塞</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Nil-Channel在select中的使用"><span class="nav-number">6.2.</span> <span class="nav-text">Nil Channel在select中的使用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Timers"><span class="nav-number">7.</span> <span class="nav-text">Timers</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#超时机制Timeout"><span class="nav-number">7.1.</span> <span class="nav-text">超时机制Timeout</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#心跳HeartBeart"><span class="nav-number">7.2.</span> <span class="nav-text">心跳HeartBeart</span></a></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">fanglin</span>

  

  
</div>









        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/utils.js?v=7.1.0"></script>

  <script src="/js/motion.js?v=7.1.0"></script>



  
  


  <script src="/js/affix.js?v=7.1.0"></script>

  <script src="/js/schemes/pisces.js?v=7.1.0"></script>



  
  <script src="/js/scrollspy.js?v=7.1.0"></script>
<script src="/js/post-details.js?v=7.1.0"></script>



  


  <script src="/js/next-boot.js?v=7.1.0"></script>


  

  

  

  
  

<script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script>



<script src="//unpkg.com/valine/dist/Valine.min.js"></script>

<script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: true,
    notify: false,
    appId: 'jjdDCzDO6jlN5yOgAbnVwdJ3-gzGzoHsz',
    appKey: 'jnjP7aorboCG7pJV6HvdMP15',
    placeholder: 'ヾﾉ≧∀≦)o来啊，快活啊!',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false,
    lang: 'zh-cn' || 'zh-cn'
  });
</script>




  


  




  

  

  

  

  

  

  

  

  

  

  

  

  

  

</body>
</html>
